/**
 * 
 */
package algorithm.passed2;

/**
 * @author Michael
 * 
 */
public class PalindromeNumber {

	
	public boolean isPalindrome0(int x) {
		if (x < 0) return false;
		int original = x;
		int reverse = 0;
		while (original >= 10) {
			reverse = reverse * 10 + original % 10;
			original /= 10;
		}
		
		return original == x % 10 && reverse == x / 10;
	}
	
    boolean isPalindrome1(int num) {
        if (num < 0 || (num % 10 == 0 && num != 0))
		    return false;

		int reverse = 0;
		while (num >= reverse) {
		    if (reverse == num || reverse == num / 10)
		        return true;
		    reverse = reverse * 10 + num % 10;
		    num /= 10;
		}

		return false;
	}
	
	/*
	 * good for interview iteration
	 */
	public boolean isPalindrome2(int x) {
		if (x < 0)
			return false;

		int divisor = 1;
		while (x / divisor >= 10) {
			divisor *= 10;
		}

		int value = x;
		while (value >= 10) {
			int left = value / divisor;
			int right = value % 10;
			if (left != right)
				return false;
			value = (value % divisor) / 10;
			divisor = divisor / 100;
		}

		return true;
	}
	
	public static boolean isPalindromeByReversingNumber(int n) {
		if (n < 0)
			return false;

		int reverse = 0;
		int original = n;
		while (original > 0) {
			reverse = reverse * 10 + original % 10;
			original /= 10;
		}

		return n == reverse;
	}

	public static boolean isPalindromeByComparingEnds1(int n) {
		if (n < 0)
			return false;
		int divisor = 1;
		int t = n;
		while (t >= 10) { // pitfall: >
			t /= 10;
			divisor *= 10;
		}
		t = n;
		while (t >= 10) {
			int left = t / divisor;
			int right = t % 10;
			if (left != right)
				return false;
			t = (t / 10) % (divisor / 10);
			divisor /= 100;
		}
		return true;
	}

	public static boolean isPalindromeByComparingEnds(int n) {
		if (n < 0)
			return false;

		int divisor = 1;
		int copy = n;
		while (copy >= 10) {
			copy /= 10;
			divisor *= 10;
		}

		while (n >= 10) {
			int left = n / divisor;
			int right = n % 10;
			if (left != right)
				return false;
			n = (n % divisor) / 10;
			divisor /= 100;
		}

		return true;
	}

	boolean isPalindromeR(int x) {

		if (x < 0)
			return false;
		int div = 1;
		if (x < 10)
			return true;

		while (x / div >= 10)
			div *= 10;

		if ((x / div) != (x % 10))
			return false;

		return isPalindromeR((x % div) / 10);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PalindromeNumber p = new PalindromeNumber();
		if (p.isPalindrome1(101101)) {
			System.out.println(101101);
		}

		//		int total = 0;
		//		for (int i = 0; i <= 99999; i++) {
		//			if (isPalindromeByComparingEnds(i)) {
		//				System.out.println(i);
		//				++total;
		//			}
		//		}
		//		System.out.printf("Total: %d", total);
	}

}
